<template>
  <div class="home">
    <input v-model="data.myId" style="margin: 10px 30px" placeholder="自己的id" />
    <input v-model="data.otherId" placeholder="对方的id" />
    <div class="msg">
      <div v-for="(item, index) in data.msg" :key="index">
        <div v-if="item.from !== data.myId" style="text-align: left">
          {{ item.from }}：{{ item.msg }}
        </div>
        <div v-else style="text-align: right">
          {{ item.from }}：{{ item.msg }}
        </div>
      </div>
    </div>
    <input v-model="data.msgInput" style="margin: 10px 30px" />
    <input type="button" value="发送" @click="send" />
  </div>
</template>

<script setup>
import { reactive, onMounted } from "vue"
import io from "socket.io-client"


fetch("http://localhost:8360/index/test")
  .then(res => res.json())
  .then(res => {
  console.log(res);
  
  })

var socket = io('http://localhost:8360', {
  path: "/socket.io",
  // query: { "name": "测试" }
})


const data = reactive({
  myId: '',
  otherId: '',
  msg: [],
  msgInput: ''
})

function send() {
  if (data.myId && data.otherId && data.msgInput) {
    const message = {
      from: data.myId,
      to: data.otherId,
      msg: data.msgInput
    }
    // 发送信息
    socket.emit('sendMsg', message)

    data.msg.push(message)
  } else {
    alert('自己的id、对方的id、对话不能为空')
  }
}







onMounted(() => {
  socket.on("opend", function (res) {
    console.log('opend:', res)
  })
  socket.on("joined", function (res) {
    console.log('joined:', res)
  })
  socket.on("add", function (res) {
    console.log('add:', res)
    if (res.to === data.myId) {
      data.msg.push(res)
    }
  })
})

</script>


<style scoped>
.msg {
  border: solid 1px #ccc;
  height: 300px;
  width: 500px;
  overflow: auto;
}

.msg::-webkit-scrollbar {
  /*滚动条整体样式*/
  width: 4px;
  height: 4px;
}

.msg::-webkit-scrollbar-thumb {
  /*滚动条里面小方块*/
  border-radius: 5px;
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  background: rgba(0, 0, 0, 0.2);
}

.msg::-webkit-scrollbar-track {
  /*滚动条里面轨道*/
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  border-radius: 0;
  background: rgba(0, 0, 0, 0.1);
}
</style>
